﻿/// <summary>
/// https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words/
/// </summary>
public class Solution
{
    private IEnumerable<string> CutString(string s, int sliceSize)
    {
        for (int i = 0; i < s.Length; i += sliceSize)
            yield return s.Substring(i, sliceSize);
    }

    private bool IsGood(string s, string[] words)
    {
        List<string> wordList = new List<string>(words);
        foreach (var cut in this.CutString(s, words[0].Length))
        {
            if (!wordList.Remove(cut))
                return false;
        }
        return true;
    }

    public IList<int> FindSubstring(string s, string[] words)
    {
        var totalWordsLength = words.Sum(item => item.Length);
        if (totalWordsLength == 0)
            return new List<int>();

        List<int> result = new List<int>();
        for (int i = 0; i < s.Length - totalWordsLength + 1; i++)
        {
            var t = s.Substring(i, totalWordsLength);
            if (this.IsGood(t, words))
                result.Add(i);
        }
        return result;
    }
}